package org.example.util;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.example.pojo.bo.ExcelInfoBO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public final class ExcelUtil {

    public static void processResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    public static void downloadExcel(HttpServletResponse response, ExcelInfoBO excelInfoBO) throws IOException {
        processResponse(response, excelInfoBO.getFileName());
        // 创建 ExcelWriter
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build()) {
            if (CollUtil.isNotEmpty(excelInfoBO.getSheetList())) {
                for (int i = 0; i < excelInfoBO.getSheetList().size(); i++) {
                    ExcelInfoBO.SheetInfo sheetInfo = excelInfoBO.getSheetList().get(i);
                    // 第一个参数是Sheet索引(0-based)，第二个是Sheet名
                    WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetInfo.getSheetName())
                            // 指定表头对应的模型类
                            .head(sheetInfo.getSheetDataClass())
                            // 注册自定义处理器，处理合并表头和下拉框
                            .registerWriteHandler(sheetInfo.getSheetWriteHandler())
                            .build();
                    excelWriter.write(sheetInfo.getSheetData(), writeSheet);
                }
            }
        }
    }

}
